package com.youu.youu.restapi.controller;


import com.atguigu.util.CommonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youu.youu.manager.bean.TBlog;
import com.youu.youu.manager.bean.TUser;
import com.youu.youu.restapi.service.BlogService;
import com.youu.youu.restapi.service.MessageService;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cc
 * @create 2017-08-11 14:34
 * @desc  用于控制EUditor的部分功能
 **/
@Controller()
@RequestMapping("/blog")
public class UEditorControlller {
    @Autowired
    BlogService blogService;
    
    @Autowired
    MessageService messageService;


    /**
     * 修改已存在博文
     * (因将在数据库博文创建时间字段设为varchar ,导致无法根据时间排序。
     * 只能重新创建一个Blog对象,删除旧的，根据Id排序)
     * @param bolgId
     * @param blogContent
     * @param blogTitle
     * @param userId
     * @param loginacct
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/editorExistBlog")
    public boolean editorExistBlog(@RequestParam("blogId")Integer bolgId,
                                   @RequestParam("blogContent") String blogContent,
                                   @RequestParam("bolgTitle") String blogTitle,
                                   @RequestParam("userId") Integer userId,
                                   @RequestParam("loginacct")String loginacct,HttpServletRequest request){
        //System.out.println("=====================================");
        //获取某个文件夹在服务器上的真实路径
        ServletContext context = request.getSession().getServletContext();
        //用context对象获取真实路径
        String userFileRootPath = context.getRealPath("/personalFile");

        //获取当前用户文件目录
        String userFilePackageName = loginacct;
        String currentUserFileRootPath = userFileRootPath + "/" + userFilePackageName;

        //博客内容写入文件中
        //存放博客文件文件名
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        String saveBlogFileName = date.getTime() + "_" + blogTitle + ".html";
        //存放博客文件绝对路径
        String saveBlogPath = currentUserFileRootPath + "/" + saveBlogFileName;
        //存放博客文件相对路径
        String saveBlogRelativePath = "/personalFile/"+userFilePackageName+"/" + saveBlogFileName;
        //创建保存博文的文件对象
        File saveBlogFile = new File(currentUserFileRootPath,saveBlogFileName);
        if (!saveBlogFile.exists()){
            try {
                //创建博文文件(此时为空)
                saveBlogFile.createNewFile();
                //向文件写入对象写入信息
                FileOutputStream fileOutputStream = new FileOutputStream(saveBlogFile);
                //写文件
                byte[] blogContentByte = blogContent.getBytes();
                fileOutputStream.write(blogContentByte);
                //关闭流
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //以下保存该条博客的关键信息
        TBlog tBlog = new TBlog();
        tBlog.setUserId(userId);  //用户id
        tBlog.setUserName(loginacct);
        tBlog.setBlogDate(dateString);  //博客创建日期
        tBlog.setBlogTitle(blogTitle);          //博客标题
        tBlog.setBlogContent(saveBlogRelativePath); //博客文件路径

        //保存博客
        boolean flat01 =  blogService.saveBlog(tBlog);
        //System.out.println("保存成功");
    //-----------------------------------------------------------------------------------
        boolean flat02 = blogService.removeBlog(bolgId);//删除旧的博文

        if (flat01 && flat02){
            return true;
        }

        return false;
    };


    /**
     * 根据博文Id删除博客
     * @param bolgId
     * @return
     */
    @ResponseBody
    @RequestMapping("/removeBlog")
    public boolean removeBlog(@RequestParam("blogId")Integer bolgId){
        System.out.println(bolgId);
         //博文删除成功发送消息给用户
        TBlog blog = blogService.getBlog(bolgId);
        messageService.addMsg(blog.getUserId(), 34, new String[]{blog.getUserName(),
                CommonUtils.simpleFormatDate(new Date()), blog.getBlogTitle()});
        boolean flat = blogService.removeBlog(bolgId);
        return flat;
    }


    /**
     * 根据博文Id获取 博文详细信息
     * @param bolgId
     * @return
     */
    @ResponseBody
    @RequestMapping("/editUserBlog")
    public TBlog editUserBlog(@RequestParam("blogId")Integer bolgId){
        TBlog tBlog = blogService.getBlog(bolgId);
        return tBlog;
    }


    /**
     * 根据用户Id获取该用户所有博文
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/showBlogList")
    public PageInfo<TBlog> showBlogList(@RequestParam("userId") Integer userId,
                                    @RequestParam(value="pn",defaultValue="1")Integer pn){
        //System.out.println("获取博文列表");
        PageHelper.startPage(pn, 5);

        List<TBlog> tBlogs = blogService.showBlogList(userId);
        //System.out.println(tBlogs);
        PageInfo<TBlog> info = new PageInfo<>(tBlogs,5);
        return info;
    }



    /**
     * 获取博文
     * @author cc
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getBlog", produces="text/html; charset=utf-8")
    public String getContent(@RequestParam("id")Integer id){
        //获取当前博客对象
        TBlog tBlog = blogService.getBlog(id);
        //获取博文存放路径
        String blogFilePath = tBlog.getBlogContent();

        return blogFilePath;
    }

    /**
     * 保存博文
     * @param blogContent
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/saveBlog", produces="application/json; charset=utf-8")
    public boolean saveContent(@RequestParam("blogContent") String blogContent,
                               @RequestParam("bolgTitle") String blogTitle,
                               @RequestParam("userId") Integer userId,
                               @RequestParam("loginacct")String loginacct,HttpServletRequest request){
        //System.out.println("=====================================");
        //获取某个文件夹在服务器上的真实路径
        ServletContext context = request.getSession().getServletContext();
        //用context对象获取真实路径
        String userFileRootPath = context.getRealPath("/personalFile");

        //获取当前用户文件目录
        String userFilePackageName = loginacct;
        String currentUserFileRootPath = userFileRootPath + "/" + userFilePackageName;

        //博客内容写入文件中
        //存放博客文件文件名
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        String saveBlogFileName = date.getTime() + "_" + blogTitle + ".html";
        //存放博客文件绝对路径
        String saveBlogPath = currentUserFileRootPath + "/" + saveBlogFileName;
        //存放博客文件相对路径
        String saveBlogRelativePath = "/personalFile/"+userFilePackageName+"/" + saveBlogFileName;
        //创建保存博文的文件对象
        File saveBlogFile = new File(currentUserFileRootPath,saveBlogFileName);
        if (!saveBlogFile.exists()){
            try {
                //创建博文文件(此时为空)
                saveBlogFile.createNewFile();
                //向文件写入对象写入信息
                FileOutputStream fileOutputStream = new FileOutputStream(saveBlogFile);
                //写文件
                byte[] blogContentByte = blogContent.getBytes();
                fileOutputStream.write(blogContentByte);
                //关闭流
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //以下保存该条博客的关键信息
        TBlog tBlog = new TBlog();
        tBlog.setUserId(userId);  //用户id
        tBlog.setUserName(loginacct);
        tBlog.setBlogDate(dateString);  //博客创建日期
        tBlog.setBlogTitle(blogTitle);          //博客标题
        tBlog.setBlogContent(saveBlogRelativePath); //博客文件路径

        //保存博客
        boolean flat =  blogService.saveBlog(tBlog);
        //System.out.println("保存成功");
        
        // 保存博客成功将发送一条消息给用户
        if (flat) {
        	messageService.addMsg(tBlog.getUserId(), 32, new String[]{loginacct, tBlog.getBlogTitle()});
		}
        
        return flat;
    }


    /**
     * 保存图片
     * @author cc
     * @param upfile
     * @param request
     * @return  Map<String,String> 返回结果信息(UEditor需要)
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/uploadImage")
    public Map<String,String> uploadImage(@RequestParam("upfile") CommonsMultipartFile upfile,
                                          @RequestParam("loginacct") String loginacct,HttpServletRequest request)
            throws IOException {
        //获取某个文件夹在服务器上的真实路径
        ServletContext context = request.getSession().getServletContext();
        //用context对象获取真实路径
        String userFileRootPath = context.getRealPath("/personalFile");

        //获取当前用户文件目录
        String userFilePackageName = loginacct;
        String currentUserFileRootPath = userFileRootPath + "/" + userFilePackageName;


        //获取服务器根目录
        //ServletContext servletContext = request.getSession().getServletContext();
        //String realPath = servletContext.getRealPath("/");
        //System.out.println("存图片realPath="+realPath);

        //这里upfile是config.json中图片提交的表单名称
        //文件原名称
        String fileName=upfile.getOriginalFilename();
        System.out.println(fileName);
        //为了避免重复简单处理
        String nowName=new Date().getTime()+"_" + fileName;

        //if(!upfile.isEmpty()){
        //    //上传位置路径
        //    String path0 = realPath+"upload/"+nowName;
        //    //按照路径新建文件
        //    File newFile = new File(path0);
        //    //复制
        //    FileCopyUtils.copy(upfile.getBytes(), newFile);
        //}

        //创建个人存放图片的文件夹
        File filePackage = new File(currentUserFileRootPath+"/img");
        if(!filePackage.exists()){
            filePackage.mkdir();//创建文件夹(存放图片)
        }else{
            System.out.println("已有图片文件夹");
        }

        //保存图片到个人图片文件夹
        if(!upfile.isEmpty()){
            //上传位置路径
            String path0 = currentUserFileRootPath+"/img/"+nowName;
            //按照路径新建文件
            File newFile = new File(path0);
            //复制
            FileCopyUtils.copy(upfile.getBytes(), newFile);
        }
        //返回结果信息(UEditor需要)
        Map<String,String> map = new HashMap<String,String >();

        //是否上传成功
        map.put("state", "SUCCESS");

        //现在文件名称
        map.put("title", nowName);

        //文件原名称
        map.put("original", fileName);

        //文件类型 .+后缀名
        map.put("type", fileName.substring(upfile.getOriginalFilename().lastIndexOf(".")));
        //文件路径
        map.put("url", "/youu-restapi/blog/"+nowName+"/getImage/"+loginacct);

        //文件大小（字节数）
        map.put("size", upfile.getSize()+"");
        //System.out.println("走controller上传成功");
        return map;

    }


    /**
     * 读取图片
     * @author cc
     * @param imgName
     * @param response
     * @throws Exception
     */
    @RequestMapping("/{imgName}/getImage/{loginacct}")
    public void readImg(@PathVariable("imgName") String imgName,
            @PathVariable("loginacct") String loginacct, HttpServletResponse response, HttpServletRequest request)
            throws Exception {

        //获取某个文件夹在服务器上的真实路径
        ServletContext context = request.getSession().getServletContext();
        //用context对象获取真实路径
        String userFileRootPath = context.getRealPath("/personalFile");

        //获取当前用户文件目录
        String userFilePackageName = loginacct;
        String currentUserFileRootPath = userFileRootPath + "/" + userFilePackageName;

        //获取服务器根目录
        //ServletContext servletContext = request.getSession().getServletContext();
        //String realPath = servletContext.getRealPath("/");
        //System.out.println("取图片realPath="+realPath);

        //设置文件的返回类型
        response.setContentType("image/*");
        //文件路径(必须是绝对路径)
        String imgPath = currentUserFileRootPath+"/img/"+imgName;

        //File类来表示一个文件
        File image = new File(imgPath);

        //测试这个文件路径是否存在（也就是这个文件是否存在）
        if (!image.exists()) {
            String flat = "图片不存在";
            byte[] flat0 = flat.getBytes();
            response.getOutputStream().write(flat0);
            return ;
        }

        //FileUtils.readFileToByteArray(File file)把一个文件转换成字节数组返回
        response.getOutputStream().write(FileUtils.readFileToByteArray(image));

        //java在使用流时,都会有一个缓冲区,按一种它认为比较高效的方法来发数据:
        //把要发的数据先放到缓冲区,缓冲区放满以后再一次性发过去,而不是分开一次一次地发.
        //而flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满.
        response.getOutputStream().flush();
        response.getOutputStream().close();

    }
}
